/**
 * desc: 公用上传图片接口
 * @img {str} require: false 单个用于回显的图片
 * @maxCount {num} require: fasle 最多上传的图片数量,不传的话默认为单张图片
 * @fileList {array} require: fasle 上传之后的图片列表，和maxCount同时出现
 * @size {num} require: false 限制图片大小 ，以兆为单位
 * @isCrop {boolean} require: false 图片是否需要裁剪(必传,默认为false)
 * @className {str} require: false 用来设置图片上传框以及上传之后的尺寸大小middle,large,small不传为默认default(84))
 * @handleOk {func} require: true 图片上传完毕之后把图片返回
 * @handleError {func} require: false 图片上传失败之后调用的方法
 * @disabled {boolean} require: false 	是否禁用
 * @upLoadText {str} require: 上传文字(默认为上传)
 * @zIndex {num} require:false 文件预览弹窗层级
 * @antPreview {boolean} require: false 是否使用anrt的预览
 */
import React from "react";
import { Upload, message, Image } from "antd";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { Base64 } from "js-base64";
import { getToken } from "@/utils/authority";
import ImgCrop from "antd-img-crop";
import CommonLoading from "@/components/CommonLoading";
import CommonModal from "../CommonModal";
import { httpChange } from "@/utils/utils.jsx";
import "./index.less";

const clientId = "sword"; // 客户端id
const clientSecret = "sword_secret"; // 客户端密钥

function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = error => reject(error);
	});
}

class Avatar extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			loading: false,
			previewVisible: false,
			previewImage: undefined,
			imageUrl: "",
			fileList: props.img
				? [
						{
							uid: "-1",
							name: "image.png",
							status: "done",
							url: props.img
						}
					]
				: props.fileList || [],
			urlAction: `${httpChange(UPLOAD_SERVER)}/zjf-oms/files/uploadFile`, //图片的上传地址
			zIndex: props.zIndex,
			antPreview: props.antPreview || false,
			failed: {} // 上传失败原因
		};
	}

	beforeUpload(file) {
		const { size = 5 } = this.props;
		const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/jpg";
		if (!isJpgOrPng) {
			this.setState({ failed: { code: -1, isJpgOrPng } });
			!this.props.handleError && message.error("只能上传JPG/JPEG/PNG格式的图片!");
		}
		//默认限制尺寸5兆
		const isLt2M = file.size / 1024 / 1024 < size;
		if (!isLt2M) {
			this.setState({ failed: { code: -1, isLt2M } });
			!this.props.handleError && message.error(`图片大小不能超过${size}M!`);
		}
		return isJpgOrPng && isLt2M;
	}

	handleChange = async ({ file, fileList }) => {
		const { maxCount = 1 } = this.props;
		if (maxCount === 1 && !file.status) {
			this.props.handleError && this.props.handleError(this.state.failed, file);

			return;
		}
		if (maxCount === 1 && file.status === "uploading") {
			this.setState({ loading: true });
		}
		if (maxCount === 1 && file.status === "done") {
			const imgUrl = await getBase64(file.originFileObj);
			this.setState({
				imageUrl: imgUrl,
				loading: false
			});
			if (file.response.code == 0) {
				if (file?.response?.data?.fullPath) {
					const str = file.response.data.fullPath,
						reg = /^(http|https)/;
					if (reg.test(str)) {
						this.props.handleOk && this.props.handleOk(file.response.data.fullPath);
					} else {
						this.props.handleOk && this.props.handleOk(QI_NIU_IMG_UPLOAD + file.response.data.fullPath);
					}
				} else {
					fileList.splice(0, 1);
				}
			} else {
				message.info(file.response.msg);
				fileList.splice(0, 1);
			}
		}
		if (maxCount === 1 && file.status === "removed") {
			this.props.handleOk && this.props.handleOk(undefined);
		}
		if (maxCount > 1 && file.status === "done") {
			//批量上传成功，length肯定至少为1，只format最后一个的路径
			const lastIndex = fileList.length - 1;
			if (file.response.code == 0) {
				if (fileList[lastIndex]?.response?.data?.fullPath) {
					const str = fileList[lastIndex].response.data.fullPath,
						reg = /^(http|https)/;
					if (!reg.test(str)) {
						fileList[lastIndex].response.data.fullPath = QI_NIU_IMG_UPLOAD + str;
					}
				} else {
					fileList.splice(lastIndex, 1);
				}
			} else {
				message.info(file.response.msg);
				fileList.splice(lastIndex, 1);
			}
		}
		this.setState({ fileList: [...fileList] }, () => {
			if (maxCount > 1) {
				this.props.handleOk && this.props.handleOk(fileList);
			}
		});
	};

	handlePreview = async file => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj);
		}
		this.setState({
			previewImage: file.url || file.preview,
			previewVisible: true,
			previewTitle: file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
		});
	};

	handleCancel = () => this.setState({ previewVisible: false });

	//根据maxCount展示loading状态
	loadingRender = () => {
		const { maxCount = 1, img, upLoadText, customNode } = this.props;
		const { imageUrl, fileList } = this.state;
		const uploadButton = customNode || (
			<div>
				{this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
				<div className="upLoad-text" style={{ marginTop: 8 }}>
					{upLoadText}
				</div>
			</div>
		);

		if (maxCount === 1) {
			if (fileList.length > 0) {
				// return <img src={imageUrl || img} alt="avatar" className="uploadImg" />;
				return null;
			} else {
				return uploadButton;
			}
		} else {
			if (fileList.length < maxCount) {
				return uploadButton;
			}
		}
	};

	render() {
		const headers = {
			Authorization: `Basic ${Base64.encode(`${clientId}:${clientSecret}`)}`,
			"Blade-Auth": getToken()
		};

		const { className = "default", maxCount = 1, isCrop = false, disabled = false } = this.props;
		const { previewVisible, previewImage, fileList = [], loading, urlAction, zIndex, antPreview } = this.state;

		const props = {
			//裁剪弹窗的属性配置
			grid: true,
			width: 500, //裁剪宽度
			height: 300, //裁剪高度
			resize: false, //裁剪是否可以调整大小
			resizeAndDrag: true, //裁剪是否可以调整大小、可拖动
			modalTitle: "上传图片", //弹窗标题
			modalWidth: 600 //弹窗宽度
		};

		const uploadContent = (
			<Upload
				data={{ type: "QINIU" }}
				name="file"
				headers={headers}
				listType="picture-card"
				className={className}
				// showUploadList={maxCount === 1 ? false : true}
				action={urlAction}
				beforeUpload={this.beforeUpload.bind(this)}
				onChange={this.handleChange}
				accept=".jpg,.jpeg,.png"
				maxCount={maxCount}
				fileList={fileList}
				disabled={disabled}
				onPreview={this.handlePreview}
				onRemove={this.handleRemove}
			>
				{this.loadingRender()}
			</Upload>
		);

		return (
			<>
				{isCrop ? <ImgCrop {...props}>{uploadContent}</ImgCrop> : uploadContent}
				{antPreview ? (
					<Image
						src={previewImage}
						preview={{
							visible: previewVisible,
							src: previewImage,
							onVisibleChange: value => {
								this.setState({ previewVisible: value });
							}
						}}
						style={{ display: "none" }}
					/>
				) : (
					<>
						<CommonModal visible={previewVisible} title="图片预览" zIndex={zIndex} footer={null} onCancel={this.handleCancel}>
							<img alt="" style={{ width: "100%" }} src={previewImage} />
						</CommonModal>
						<CommonLoading loading={loading} />
					</>
				)}
			</>
		);
	}
}

export default Avatar;
